import { GlobalEvent } from "./GlobalEvent";
import { ConstData } from "./ConstData";
import { GlobalFunction } from "./GlobalFunction";

export class sceneMgr {

    private static _instance:sceneMgr = new sceneMgr();
    static Ins()
    {
        return this._instance;
    }

    private sceneList : string[] = [];
    private curScene : number;

    init(firstSceneName:string){
        GlobalEvent.on(GlobalEvent.Event.enterScene, function(event){
            this.enter(event.SceneName);
        }.bind(this), this);

        GlobalEvent.on(GlobalEvent.Event.backScene, function(event){
            this.back();
        }.bind(this), this);

        sceneMgr.Ins().enter(firstSceneName);

        cc.log("场景管理器初始化完成");
    }

    private async loadingScene(sceneName:string){
        await GlobalFunction.asyncLoadScene("loading")
        await GlobalFunction.asyncPreloadScene(sceneName, function(completedCount, totalCount, item){
            GlobalEvent.emit(GlobalEvent.Event.loadingSceneProgress, {
                completedCount:completedCount, 
                totalCount:totalCount, 
                item:item
            });
        });
        cc.sys.garbageCollect();
    }

    private async enter(sceneName:string)
    {
        await this.loadingScene(sceneName);
        await GlobalFunction.asyncLoadScene(sceneName);
        this.sceneList.push(sceneName);
        this.curScene = this.sceneList.length - 1;
        GlobalEvent.emit(GlobalEvent.Event.loadingSceneComplete, {
            PreSceneName:this.getScene(this.curScene-1), 
            CurSceneName:this.getScene(this.curScene),
        });
    }

    private async back()
    {
        if(this.sceneList.length > 1)
        {
            var index = this.curScene-1;
            var sceneName = this.sceneList[index];
            await this.loadingScene(sceneName);
            await GlobalFunction.asyncLoadScene(sceneName);
            this.sceneList.pop();
            this.curScene = index;
            GlobalEvent.emit(GlobalEvent.Event.loadingSceneComplete, {
                PreSceneName:this.getScene(this.curScene-1), 
                CurSceneName:this.getScene(this.curScene),
            });
        }
    }

    private getScene(index){
        if(index < 0) return null;
        return this.sceneList[index];
    }
}
